package com.twu.biblioteca.controller;

import com.twu.biblioteca.io.InputReader;
import com.twu.biblioteca.model.User;
import com.twu.biblioteca.ui.LibraryView;
import com.twu.biblioteca.ui.UserView;
import com.twu.biblioteca.util.Messages;
import com.twu.biblioteca.util.UserDetails;

import java.util.StringTokenizer;

/**
 * Created by madhu on 1/5/14.
 */
public class UserController {

    private UserView userView;

    public UserController() {
        userView = new UserView();
    }

    public void login() {

        InputReader inputReader = new InputReader();
        userView.displayPromptMessage(Messages.libraryNumberPromptMessage);
        String libraryNumber = inputReader.getUserInput();
        userView.displayPromptMessage(Messages.passwordPromptMessage);
        String password = inputReader.getUserInput();

        boolean isAuthenticated = authenticateUser(libraryNumber, password);
        if(isAuthenticated) {
            userView.displayPromptMessage(Messages.successfulLoginMessage);
            loadAndStoreUserDetails(libraryNumber);
        }
        else
            userView.displayPromptMessage(Messages.unsuccessfulLoginMessage);

    }

    private void loadAndStoreUserDetails(String libraryNumber) {

        //Loading current user's details
        UserDetails userDetails = new UserDetails("user_info.properties");
        String[] userInfo = parseUserInfo(userDetails.getUserDetails(libraryNumber), ":");

        //Storing current user's details
        User user = User.getInstance(userInfo[0], userInfo[1], userInfo[2], libraryNumber);

    }

    private String[] parseUserInfo(String userDetails, String delimiter) {
        return userDetails.split(delimiter);
    }

    public boolean authenticateUser(String libraryNumber, String password) {
        UserDetails userDetails = new UserDetails("user_credentials.properties");
        String actualPassword = userDetails.getUserDetails(libraryNumber);
        if(actualPassword==null || !actualPassword.equals(password))
            return false;
        return true;
    }

    public static void promptForLogin(LibraryView libraryView) {
        libraryView.displayErrorMessage(Messages.loginPromptMessage);
    }
}
